package com.yf.course.modules.course.utils;

import com.yf.base.enums.OpenType;
import com.yf.course.enums.CourseState;
import com.yf.course.modules.course.service.CourseDepartService;
import com.yf.course.modules.course.service.CourseLearnDailyService;
import com.yf.course.modules.course.service.CoursePersonService;
import com.yf.system.modules.user.entity.SysUser;
import com.yf.system.modules.user.service.SysUserService;
import com.yf.system.utils.DateRangeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 课程状态处理工具
 * @author van
 */
@Component
public class CourseStateUtils {


    @Autowired
    private CoursePersonService coursePersonService;

    @Autowired
    private CourseDepartService courseDepartService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CourseLearnDailyService courseLearnDailyService;

    /**
     * 课程状态处理工具
     * @param courseId
     * @param state
     * @param userId
     * @param openType
     * @param dayLimit
     * @param startTime
     * @param endTime
     * @param dayRule
     * @return
     */
    public int modifyState(String courseId, Integer state, String userId, Integer openType, Integer dayLimit, Date startTime, Date endTime, String dayRule){


        // 禁用直接返回
        if(state==null || state.equals(1)){
            return state;
        }

        // 未开始
        if(startTime!=null
                && new Date().before(startTime)){
            return CourseState.PREPARE;
        }

        // 已结束了
        if(endTime!=null && new Date().after(endTime)){
            return CourseState.ENDED;
        }

        // 每日学习时间限时
        if(StringUtils.isNotBlank(dayRule)){
            String [] arr = dayRule.split("\n");
            boolean inRange = DateRangeUtils.inRange(arr);
            if(!inRange){
                // 不在可学习时间
                return CourseState.NOT_IN_TIME;
            }
        }

        // 限制时间
        if (dayLimit != null && dayLimit > 0) {
            Long learnSec = courseLearnDailyService.daily(courseId, userId);
            if (learnSec >= dayLimit*60) {
                return CourseState.OVER_TIME;
            }
        }

        // 人员开放的
        if(OpenType.PERSON.equals(openType)){
            boolean in = coursePersonService.inList(courseId, userId);
            if(!in){
                return CourseState.NOT_IN_PERSON;
            }
        }

        // 部门开放的
        if(OpenType.DEPART.equals(openType)){
            SysUser user = sysUserService.getById(userId);
            boolean in = courseDepartService.inList(courseId, user.getDeptCode());
            if(!in){
                return CourseState.NOT_IN_DEPART;
            }
        }

        return state;

    }



}
